<template>
    <div class="category-detail-page">
        <el-card shadow="never">
            <el-form
                :model="form"
                label-position="right"
                label-suffix=":"
                label-width="250px"
                ref="form"
                :rules="rules">
                <el-form-item label="主题名称" prop="name">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入学习主题名称"
                        class="input-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="主题描述" prop="context">
                    <el-input
                        v-model="form.context"
                        placeholder="请输入主题描述"
                        class="input-width"
                        type="textarea"
                        autosize
                    ></el-input>
                </el-form-item>
                <el-form-item label="必备关键技能项">
                    <div v-for="(item, i) in skillsList" :key="i">
                        <el-input
                            v-model="item.val"
                            placeholder="请输入必备关键技能项"
                            class="input-width mr-4"
                            type="text"
                            autosize></el-input>
                        <el-button type="text" @click="onDelete(i)" v-if="skillsList.length > 1">
                            <i class="el-icon-close"></i>
                        </el-button>
                    </div>
                    <div class="my-4"></div>
                    <el-button type="primary" @click="onAddSkills">添加</el-button>
                </el-form-item>
                <!-- <el-form-item label="学习内容和收获" prop="content">
                    <el-input
                        v-model="form.content"
                        placeholder="概述学习内容要点和潜在收获"
                        class="input-width"
                        type="textarea"
                        autosize
                    ></el-input>
                </el-form-item> -->
                <el-form-item label="选择主题分类" prop="category_id">
                    <el-select
                        v-model="form.category_id"
                        placeholder="为该学习主题选择一个学习阶梯或分类"
                        class="input-width">
                        <el-option
                            v-for="item in labelCategoryOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <!-- <el-form-item label="是否作为“我的角色地图”栏目学习卡" prop="is_custom">
                    <el-radio v-model="form.is_custom" :label="true">是</el-radio>
                    <el-radio v-model="form.is_custom" :label="false">否</el-radio>
                </el-form-item> -->
                <el-form-item label="关联一个学习路径">
                    <el-button type="primary" @click="getLabels">{{ "关联学习路径" }}</el-button>
                    <label-list
                        v-show="form.labels.length > 0"
                        :list="form.labels"
                        @delete="deleteLabel"></label-list>
                </el-form-item>
                <!-- <el-form-item label="涉及的知识、能力">
                    <el-button type="primary" @click="editData">逐条添加</el-button>
                    <el-table v-if="capabilityData.length" :data="capabilityData">
                        <el-table-column label="概述内容">
                            <template slot-scope="{ row }">
                                <el-input
                                    type="textarea"
                                    placeholder="请输入概述内容"
                                    v-model="row.value"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="180">
                            <template slot-scope="{ $index }">
                                <el-button
                                    type="text"
                                    class="red-color"
                                    @click="editData($index)">移除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-form-item> -->
                <label-dialog ref="label" :list="form.label_ids" @addLabel="addLabelHandle"></label-dialog>
            </el-form>
            <div class="text-center">
                <el-button :loading="posting" type="primary" @click="onSave">保 存</el-button>
            </div>
        </el-card>
    </div>
</template>

<script>
import LabelDialog from '../../components/dialog/LabelDialog';
import LabelList from '../../components/page/LabelList';

export default {
    components: {
        LabelDialog,
        LabelList,
    },
    data() {
        return {
            capabilityData: [],

            posting: false,
            form: {
                name: '',
                context: '',
                content: '',
                label_ids: [],
                category_id: '',
                labels: [],
                company_id: '',
                is_custom: false,
                capability_list: [],
                skills: [],
            },
            skillsList: [
                {val: ''},
            ],

            id: this.$route.params.id,
            labelCategoryOptions: [],
            labelOptions: [],
            originLabels: [],
            listForm: {
                type: 2,
                companyId: this.$store.state.my.company_id,
            },
            rules: {
                name: [
                    { required: true, message: '学习主题名称不能为空', trigger: 'blur' },
                ],
                context: [
                    { required: true, message: '主题描述不能为空', trigger: 'blur' },
                ],
                // content: [
                //     { required: true, message: '学习内容和收获不能为空', trigger: 'blur' },
                // ],
                category_id: [
                    { required: true, message: '学习阶梯属性不能为空', trigger: 'blur' },
                ],
            },
        };
    },
    methods: {
        editData(i) {
            const data = this.capabilityData;
            if (typeof i === 'number') {
                data.splice(i, 1);
            } else data.push({value: ''});
        },

        onSave() {
            const capabilityData = this.capabilityData;
            const capabilityArr = [];

            for (const item of capabilityData) {
                if (item.value) capabilityArr.push(item.value);
            }

            this.$refs.form.validate(async (valid) => {
                if (!valid) return;
                this.posting = true;

                this.form.capability_list = capabilityArr;

                const skillsList = this.skillsList;
                const skillsArr = [];
                for (const item of skillsList) {
                    if (item.val) skillsArr.push(item.val);
                }
                this.form.skills = skillsArr;

                if (this.id) {
                    const res = await API.get(`course/bind/${this.id}`);
                    this.getDiffLabelIds(res);
                    API.put(`course/${this.id}`, this.form).then(() => {
                        this.posting = false;
                        // this.$router.push({name: 'CourseManage'});
                        $ele.$message.success('保存成功');
                        this.$router.go(-1);
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                } else {
                    this.getDiffLabelIds([]);
                    API.post('course', this.form).then(() => {
                        this.posting = false;
                        this.$router.push({name: 'CourseManage'});
                    }).catch(err => {
                        $ele.$message.error(err.message);
                    }).finally(() => this.posting = false);
                }
            });
        },
        fetchData() {
            if (this.id) {
                API.get(`course/${this.id}`).then((res) => {
                    for (const i of Object.keys(this.form)) {
                        if (res[i] || res[i] === 0) this.form[i] = res[i];
                    }
                    this.originLabels = res.label_ids;

                    this.capabilityData = [];
                    for (const item of this.form.capability_list) {
                        this.capabilityData.push({value: item});
                    }

                    const skillsList = [];
                    for (const item of res.skills) {
                        skillsList.push({val: item});
                    }
                    this.skillsList = skillsList;
                });
            }
        },
        fetchLabelCategory() {
            API.get('category/list', {params: this.listForm}).then((res) => {
                this.labelCategoryOptions = res;
            });
        },
        fetchLabel() {
            API.get('label/list').then((res) => {
                this.labelOptions = res;
            });
        },
        getDiffLabelIds(res) {
            this.form.add_label_ids = this.form.label_ids.filter(v => res.indexOf(v) === -1);
            this.form.del_label_ids = res.filter(v => this.form.label_ids.indexOf(v) === -1);
        },
        addLabelHandle(label) {
            if (!this.form.label_ids.includes(label.id)) {
                this.form.labels.push(label);
                this.form.label_ids = [];
                this.form.labels.map((el) => {
                    this.form.label_ids.push(el.id);
                    return el;
                });
            }
            $ele.$message.success('选择学习路径（岗位角色/学习计划/专题）成功');
        },
        getLabels() {
            this.$refs.label.open();
        },
        deleteLabel(index) {
            this.form.labels.splice(index, 1);
            this.form.label_ids = [];
            this.form.labels.map((el) => {
                this.form.label_ids.push(el.id);
                return el;
            });
        },

        onAddSkills() {
            this.skillsList.push({val: ''});
        },

        onDelete(i) {
            this.skillsList.splice(i, 1);
        },
    },
    mounted() {
        this.fetchData();
        this.fetchLabelCategory();
    },
};
</script>

<style lang="scss">
.category-detail-page {
    .input-width {
        width: 300px;
    }
    .picture {
        width: 200px;
        height: 200px;
        line-height: 200px;
    }
    .uploader-icon {
        font-size: 20px;
        color: #8c939d;
        text-align: center;
    }
    .image-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
}
</style>
